package com.nwpu.intimacy.keword;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.friend.FriendInformationActivity;
import com.nwpu.intimacy.utils.CacheUtil;

public class KeywordActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/keyword";

	private final static int USER_SEARCH_SUCCESS = 0x114;
	private final static int USER_SEARCH_FAIL = 0x115;

	private ImageView back;
	private EditText editText_search;
	private ImageView ivDeleteText_keyword;

	private ProgressDialog progressDialog;

	private Handler searchHandler;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		getActionBar().hide();

		initLayout();

		// 监听删除按钮点击事件
		ivDeleteText_keyword.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				editText_search.setText("");
			}
		});

		// 监听文本框事件
		editText_search.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				if (s.length() == 0) {
					ivDeleteText_keyword.setVisibility(View.GONE);
				} else {
					ivDeleteText_keyword.setVisibility(View.VISIBLE);
				}
			}
		});

		// 监听回退事件
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();

			}
		});

		editText_search.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				final String searchInformation = editText_search.getText()
						.toString();

				// 判断输入框中是否填写了内容
				if (searchInformation.equals("")) {

					return false;

				}

				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					// 先隐藏键盘
					((InputMethodManager) editText_search.getContext()
							.getSystemService(Context.INPUT_METHOD_SERVICE))
							.hideSoftInputFromWindow(KeywordActivity.this
									.getCurrentFocus().getWindowToken(),
									InputMethodManager.HIDE_NOT_ALWAYS);

					progressDialog = new ProgressDialog(KeywordActivity.this);
					progressDialog.setIcon(R.drawable.ic_launcher);
					progressDialog.setMessage("Loging....");
					progressDialog.show();

					new Thread(new Runnable() {

						@Override
						public void run() {
							try {

								Thread.sleep(1000);

								if (!isMyFriend(searchInformation)) {

									searchFriend(searchInformation);

								} else {

									startNewActivity(searchInformation);

								}

							} catch (Exception e) {
								e.printStackTrace();
							} finally {

								progressDialog.dismiss();
							}
						}
					}).start();

					return true;
				}
				return false;
			}
		});

		// 线程交互
		searchHandler = new Handler() {

			@SuppressLint("NewApi")
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_SEARCH_SUCCESS: {
					// 跳转界面 登录成功

					try {
						Toast.makeText(getApplicationContext(), "Success!",
								Toast.LENGTH_SHORT).show();

						JSONArray jsonArray = new JSONArray(msg.obj.toString());
						JSONObject jsonObject = (JSONObject) jsonArray.get(0);

						Intent intent = new Intent();
						FriendInformationActivity
								.initInformation(jsonObject
										.optString("username"), jsonObject
										.optString("sex"), jsonObject
										.optString("area"), jsonObject
										.optString("comment"), "Add Friend",
										stringtoBitmap(jsonObject
												.optString("portrait")));

						intent.setClass(getApplicationContext(),
								FriendInformationActivity.class);
						startActivity(intent);

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				case USER_SEARCH_FAIL: {

					// 登陆失败，提示用户

					Toast.makeText(getApplicationContext(),
							"No found specified user!", Toast.LENGTH_SHORT)
							.show();

				}
				default:
					super.handleMessage(msg);
				}
			}

		};

	}

	/**
	 * 初始化控件
	 */
	private void initLayout() {

		back = (ImageView) findViewById(R.id.search_keyword_back);
		editText_search = (EditText) findViewById(R.id.etSearch_keyword);
		ivDeleteText_keyword = (ImageView) findViewById(R.id.ivDeleteText_keyword);

	}

	private void searchFriend(final String str) {

		new Thread() {

			public void run() {

				try {

					// 封装用户信息
					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username", str);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"keyword", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					/*
					 * String result = new String(
					 * EntityUtils.toString(httpResponse.getEntity()),
					 * HTTP.UTF_8);
					 */

					Log.e("keyword", URLDecoder.decode(result, HTTP.UTF_8));
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("status").equals("success")) {

						Message msg = new Message();
						msg.what = USER_SEARCH_SUCCESS;
						msg.obj = result;
						searchHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_SEARCH_FAIL;
						msg.obj = result;
						searchHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

	/**
	 * 将字符串转换成Bitmap图片
	 * 
	 * @param string
	 * @return
	 */
	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	/**
	 * 判断搜索的用户是否是自己的好友
	 * 
	 * @param username
	 * @return
	 */
	public boolean isMyFriend(String username) {

		try {

			String str = CacheUtil.getFromFile("friendsInformation", "Friend");

			Log.e("str", str);

			JSONArray jsonArray = new JSONArray(str);

			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				Log.e("strstrstrstr", jsonObject.toString());
				if (jsonObject.optString("username").equals(username)) {

					return true;

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 搜索对象为好友，则直接跳转至好友信息界面
	 * 
	 * @param username
	 */
	private void startNewActivity(String username) {

		try {

			String str = CacheUtil.getFromFile("friendsInformation", "Friend");

			Log.e("str", str);

			JSONArray jsonArray = new JSONArray(str);

			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				Log.e("strstrstrstr", jsonObject.toString());
				if (jsonObject.optString("username").equals(username)) {

					Intent intent = new Intent();

					FriendInformationActivity.initInformation(
							jsonObject.optString("username"),
							jsonObject.optString("sex"),
							jsonObject.optString("area"),
							jsonObject.optString("comment"), "Delete Friend",
							CacheUtil.GetFromFile(username, "FriendPhoto"));

					intent.setClass(getApplicationContext(),
							FriendInformationActivity.class);
					startActivity(intent);

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
